package cn.com.device.monitor.mqtt;

import cn.com.device.monitor.service.IotdbService;
import cn.com.device.monitor.vo.MqttMessgeVO;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.logging.log4j.util.Strings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.integration.annotation.ServiceActivator;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Service;

/**
 * 监听消息
 */
@Service
public class MqttMessageReceiver {
    Logger logger = LoggerFactory.getLogger(MqttMessageReceiver.class);
    @Autowired
    private IotdbService iotdbService;

    /**
     * 数据格式
     * {"deviceId":"sb0001","temperature":"24","warn":"false","status":"run"}
     * @param message
     */
    @ServiceActivator(inputChannel = "mqttInputChannel")
    public void handleMessage(Message<String> message) {
        logger.info("获取MQTT设备数据："+message.getPayload());
        String deviceJson = message.getPayload();
        if(Strings.isBlank(deviceJson)){
            return;
        }
        // 进行数据解析
        try{
            ObjectMapper mapper = new ObjectMapper();
            MqttMessgeVO result =  mapper.readValue(deviceJson, MqttMessgeVO.class);
            iotdbService.save(result);
        }catch (Exception e){
            e.getStackTrace();
            logger.error("处理获取MQTT设备数据异常",e);
        }
    }
}